var utils = require('../../utils/util.js');
var base64Js = require('../../utils/base64.js');
var md5Js = require('../../utils/md5.js');
var app = getApp();
var object = {};
object.data = {};
Page({
  data:{
    details: [],
    actionSheetHidden: true,
    activeIndex: 0,
    index:0,
    minusStatuses:0,
    sku_info_checkout:[],
    num:1,
  },
  onLoad:function(options){
     try{
        var id = options.id;
        var that = this;
        //获取缓存的用户对象信息
        var user_info =  wx.getStorageSync('user_info');
        //如果用户信息不为空则请求首页接口获取产品等信息。
        if(user_info){
          var request_data = user_info.user_itmes;
          var uid         = request_data.id.toString();
          var private_key = user_info.private_key;
          var t           =  new Date().getTime().toString();
          var k           = md5Js.hex_md5(private_key+id+t);//key
          var parms_url   = app.request_url+'C_Product/'+id+'?';
          parms_url += 'enterpriseId='+request_data.enterpriseId;
          parms_url += '&channelId='+request_data.channelId;
          parms_url += '&uid='+request_data.id;
          parms_url += '&userType='+request_data.type;
          parms_url += '&t='+t;
          parms_url += '&k='+k;
          parms_url += '&v='+app.version;;
          // parms_url = 'https://rest.test.freshqiao.com/C_Product/'+id+'?enterpriseId=79&channelId=200&userType=1&t=1484817008984&k=a43cef2a5f9a7e0ea802c22b12dc02da&uid=100000261&v=2';
          //调用产品详情接口
          wx.request({
            url: parms_url,
            method: 'GET',
            success: function(res){
               var respones = res;
               //请求成功分配模板变量
               if((respones.statusCode=='200')&&(respones.data.Success==1)){
                   //分配模板变量
                   that.setData({
                       details:res.data.CallInfo
                   });
               }
            }
          })
        }
    }catch(e){
      console.log('error=>'+e.message);return false;
    }
  },
  onReady:function(){
    // 页面渲染完成
  },
  onShow:function(){
    // 页面显示
  },
  onHide:function(){
    // 页面隐藏
  },
  onUnload:function(){
    // 页面关闭
  },
  select_collection: function(event){
    try{
        var collectionId = event.target.dataset.id;
        var collectiontype = event.target.dataset.type;
        var _this = this;
        //获取缓存的用户对象信息
        var user_info =  wx.getStorageSync('user_info');
        //如果用户信息不为空则请求首页接口获取产品等信息。
        if(user_info){
          var request_data = user_info.user_itmes;
          var uid         = request_data.id.toString();
          var private_key = user_info.private_key;
          var str = 'enterprise_id='+request_data.enterpriseId+'&channel_id='+request_data.channelId+'&product_id='+collectionId+'&type='+collectiontype;
          var payload = base64Js.encode(str);
          var t           =  new Date().getTime().toString();
          var k           = md5Js.hex_md5(private_key+t+payload);//key
          var parms_url   = app.request_url+'C_Collection/?';
          parms_url += '&uid='+request_data.id;
          parms_url += '&userType='+request_data.type;
          parms_url += '&t='+t;
          parms_url += '&k='+k;
          parms_url += '&v='+app.version;
          // parms_url = 'http://rest.test.freshqiao.com/C_Collection/?userType=1&t=1485074684596&k=3187ad9a212d61fbf57e4431863db508&uid=100000202&v=2';
          //调用收藏接口
          wx.request({
            url: parms_url,
            data: {payload:payload},
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            method: 'PUT',
            success: function(res){
               var respones = res;
               //请求成功分配模板变量
               if((respones.statusCode=='200')&&(respones.data.Success==1)){
                   if(collectiontype == 0){
                      wx.showToast({
                      title: '取消成功',
                      });
                      setTimeout(function(){
                          wx.redirectTo({
                            url: '../shopdetail/shopdetail?id='+collectionId,
                          })
                      },2000)  
                   }else{
                     wx.showToast({
                        title: '收藏成功',
                     });
                      setTimeout(function(){
                        wx.redirectTo({
                          url: '../shopdetail/shopdetail?id='+collectionId,
                        })
                      },2000)
                   }                
               }
            }
          })
        }
    }catch(e){
      console.log('error=>'+e.message);return false;
    }
  },

 showModal: function (e) {
    // 显示遮罩层
    var sku_info = e.currentTarget.dataset.skuinfo;
    var product_name = e.currentTarget.dataset.productname;
    var productinfo = e.currentTarget.dataset.productinfo;
    var confirm = e.currentTarget.dataset.confirm;
    var num = e.currentTarget.dataset.num;
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      product_name:product_name,
      sku_info:sku_info,
      product_info:productinfo,
      animationData: animation.export(),
      confirm:confirm,
      showModalStatus: true
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export()
      })
    }.bind(this), 200)
  },
  hideModal: function () {
    // 隐藏遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export(),
        showModalStatus: false
      })
    }.bind(this), 200)
  },


bindMinus: function(e) {
    var index = parseInt(e.currentTarget.dataset.index);
    var num = this.data.num;
    // 如果只有1件了，就不允许再减了
    if (num > 1) {
      num --;
    }
    // 只有大于一件的时候，才能normal状态，否则disable状态
    var minusStatus = num <= 1 ? 'disabled' : 'normal';
    // 按钮可用状态
    var minusStatuses = this.data.minusStatuses;
    // 将数值与状态写回
    this.setData({
      num: num,
      minusStatuses: minusStatus
    });
  },
  bindPlus: function(e) {
    var index = parseInt(e.currentTarget.dataset.index);
    var num = this.data.num;
    // 自增
    num ++;
    // 只有大于一件的时候，才能normal状态，否则disable状态
    var minusStatus = num <= 1 ? 'disabled' : 'normal';
    // 按钮可用状态
    var minusStatuses = this.data.minusStatuses;
    // 将数值与状态写回
    this.setData({
      num: num,
      minusStatuses: minusStatus
    });
  },

  //点击添加购物车时添加商品
  submit: function(e){
    var confirm = e.currentTarget.dataset.confirm;
    var sku_info = e.currentTarget.dataset.skuinfo;
    var skuinfotmp = e.currentTarget.dataset.skuinfotmp;
    var product_info = e.currentTarget.dataset.productinfo;
    var carts_num = this.data.num;
    if(sku_info == false){
      sku_info = skuinfotmp;
    }
    var image = e.target.dataset.image
    sku_info['img_Url'] = image;
    if(confirm != 1){
      var user_info  = wx.getStorageSync('user_info');
      var order_list = product_info.id+';'+carts_num+';'+user_info.user_itmes.channelId+';'+product_info.enterprise_id+';'+sku_info.id+';';
      if(order_list){
        var parms_url  = app.request_url+'C_Order?';
        var payload_str = 'orderList='+order_list;
        var request_data = user_info.user_itmes;
        var uid         = request_data.id.toString();
        var private_key = user_info.private_key;
        var t           =  new Date().getTime().toString();
        var payload = base64Js.encode(payload_str);
        var k = md5Js.hex_md5(private_key+t+payload);
        parms_url += '&uid='+request_data.id;
        parms_url += '&userType='+request_data.type;
        parms_url += '&t='+t;
        parms_url += '&k='+k;
        parms_url += '&v='+app.version;
        wx.request({
          url: parms_url,
          method: 'POST',
          data:{payload:payload},
          header: {
                'content-type': 'application/x-www-form-urlencoded'
          },
          success: function(res){
            var respones = res;
            if((respones.statusCode=='200')&&(respones.data.Success==1)){
                  //登录成功
                  var user_items = respones.data.CallInfo;
                  //d调用异步存储api将用户信息写进缓存
                  wx.setStorage({
                    key: 'order_info',
                    data: {'order_info':user_items},
                    success: function(res){
                      setTimeout(function(){
                          wx.navigateTo({
                            url: '../orderPut/orderPut',
                          })
                      },1000)
                    },
                  })
              }else{
                  wx.showModal({
                    title:'提示',
                    content:'订单生成失败！',
                    showCancel:false,
                    confirmColor:'black'
                  })    
              }
          },
          fail: function() {
            wx.showModal({
              title:'提示',
              content:'网络异常请求失败!',
              showCancel:false,
              confirmColor:'black'
          })    
          },
        })
      }
  }else{
      var cart = require('../../utils/cart.js');
      cart.submitcart(e, this)
    }
  },

  // //点击结算时添加购物车
  // shopping: function(e){
  //   var sku_info = e.currentTarget.dataset.skuinfo;
  //   var product_name = e.currentTarget.dataset.productname;
  //   var tmp = {sku_itmes:sku_info[0],name:product_name};
  //   //加入购物车
  //   utils.addCart(tmp);
  //   //获取缓存的购物车对象信息
  //   var cart_info =  wx.getStorageSync('cart_info');
  //   this.setData({cart_num:cart_info.length});
  //   if(cart_info){
  //      wx.navigateTo({
  //       url: '../orderPut/orderPut'
  //     })
  //   }
  // },

  radioChange: function (e) {
    this.setData({
      sku_info_checkout: e.currentTarget.dataset.skuinfo,
      activeIndex: e.currentTarget.dataset.index
    });
  },

})